import { show } from "../constants/Toast";
import RNFetchBlob from 'react-native-fetch-blob';
import { api_util_uploader_main } from "./HttpServices";
import { Platform } from "react-native";
import { API_URL } from "./HttpExtension";
import TextUtil from "./TextUtil";

const handleUrl = (url) => (params) => {
    if (params) {
        let paramsArray = [];
        Object.keys(params).forEach((key) =>
            paramsArray.push(key + "=" + encodeURIComponent(params[key]))
        );
        if (url.search(/\?/) === -1) {
            typeof params === "object" ? (url += "?" + paramsArray.join("&")) : url;
        } else {
            url += "&" + paramsArray.join("&");
        }
    }
    console.log(url)
    return url;
};

//**************文件上传**************
export const uploadImage = (imgAry, Callback) => {
    console.log('imgAry', imgAry);
    let formData = new FormData();       //因为需要上传多张图片,所以需要遍历数组,把图片的路径数组放入formData中
    for (let i = 0; i < imgAry.length; i++) {
        var a = imgAry[i].uri;
        var arr = a.split('/');
        // 获取文件名end
        //      判断文件的类型(视频-图片等)end
        //判断文件的类型(视频-图片等)end
        let file = { uri: imgAry[i].uri, type: 'image/' + arr[arr.length - 1].split('.')[1], name: arr[arr.length - 1] };   //这里的key(uri和type和name)不能改变,
        formData.append('file[]', file);
    }

    console.log('formData', formData);
    let params = {
        'token': global.token ? global.token : '',
    }
    fetch(handleUrl(API_URL + api_util_uploader_main)(params), {
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
        },
        body: formData,
    })
        .then((response) => response.json())
        .then((responseData) => {
            console.log('responseData=', responseData);
            if (responseData.code == 200) {
                Callback.success(responseData);
            } else {
                Callback.fail(responseData);
            }
        })
        .catch((error) => { console.error('error=', error) });
}

export const uploadSingleImage = (res, Callback) => {
    let formData = new FormData();
    var a = res.uri;
    var arr = a.split('/');
    // 获取文件名end
    //      判断文件的类型(视频-图片等)end
    //判断文件的类型(视频-图片等)end
    let file = { uri: a, type: 'image/' + arr[arr.length - 1].split('.')[1], name: arr[arr.length - 1] };   //这里的key(uri和type和name)不能改变,
    formData.append("file", file);
    console.log('formData', formData);
    fetch(API_URL + api_util_uploader_main, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Disposition': 'form-data;filename=enctype'
        },
        body: formData,
    })
        .then((response) => response.json())
        .then((responseData) => {
            console.log('responseData=', responseData);
            if (responseData.code == 200) {
                Callback.success(responseData);
            } else {
                Callback.fail(responseData);
            }
        })
        .catch((error) => {
            console.error('error=', error)
            Callback.fail()
        });
}

//下面的是带进度回调的上传
export const uploadFile = (imgAry, setSpeed, Callback) => {
    var count = 0;
    var speed = 0;

    let list = [];
    for (let i = 0; i < imgAry.length; i++) {
        var a = imgAry[i].uri;
        var arr = a.split('/');

        list.push({
            name: 'file[]',
            filename: arr[arr.length - 1],
            type: 'image/' + arr[arr.length - 1].split('.')[1],
            data: RNFetchBlob.wrap(imgAry[i].uri),
        })
    }

    RNFetchBlob.fetch('POST', API_URL + api_util_uploader_main, {
        'Content-Type': 'multipart/form-data',
    }, list)
        .uploadProgress({ interval: 100 }, (written, total) => {
            speed = written - count;
            count = written;
            var speedT = '';
            var speedTime = '';
            var progress = written / total;
            var surplus = total - written;
            console.log('uploaded:', total / 1024 * 10)  //kb/s
            if (speed / 1024 * 10 > 1024) {
                speedT = fmoney(speed / 1024 / 1024 * 10, 2) + 'mb/s';
            } else {
                speedT = fmoney(speed / 1024 * 10, 2) + 'mb/s';
            }
            if (surplus / speed < 60) {
                speedTime = fmoney(surplus / speed, 2) + '秒';
            } else if (surplus / speed / 60 < 60) {
                speedTime = fmoney(surplus / speed / 60, 2) + '分钟';
            } else {
                speedTime = fmoney(surplus / speed, 2) + '小时';
            }
            // setSpeed(speedT, speedTime, progress)
            setSpeed(TextUtil.save2double(progress * 100) + '%')
        })
        .then((resp) => resp.json())
        .then((response) => {
            console.log('responseData=', response);
            if (response) {
                if (response.status == 'success') {
                    return Callback.success(response);
                } else {
                    Callback.fail();
                    show(response.msg);
                }
            }
        })
        .catch((err) => {
            console.log(err);
            Callback.fail();
        })
}

export const fmoney = (s, n) => {
    if (s === '')
        return;
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    var t = "";
    for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
}
